//
//  UIApplication+Extension.swift
//  Utility
//
//  Created by 于虎拴 on 2023/2/2.
//

import Foundation
import UIKit

public extension UIApplication {
  /// 前台活动 UIWindowScene
  var foregroundActiveScene: UIWindowScene? {
    connectedScenes
      .filter { $0.activationState == .foregroundActive }
      .compactMap { $0 as? UIWindowScene }
      .first
  }
  
  /// iOS 13 后，这个 API 已经被标记为弃用了
  var keyWindow: UIWindow? {
    foregroundActiveScene?
      .windows
      .first(where: { $0.isKeyWindow })
  }
  
  /// 设备方向，不受锁定屏幕方向的影响
  var deviceOrientation: UIDeviceOrientation {
    UIDevice.current.orientation
  }
  
  var interfaceOrientation: UIInterfaceOrientation? {
    UIApplication.shared.foregroundActiveScene?.interfaceOrientation
  }
  
  /// 苹果的API曾经是允许修改[UIDevice currentDevice].orientation的，后来这个接口被干掉作为私有API了
  static func setOrientation(rotateTo rotateOrientation: UIDeviceOrientation?) {
    guard let targetOrientation = rotateOrientation else { return }
    UIDevice.current.setValue(targetOrientation.rawValue, forKey: "orientation")
    // 尝试将所有窗口旋转到设备的方向
    UIViewController.attemptRotationToDeviceOrientation()
  }
}

